package opensource.xinye.com.test11

import android.app.Activity
import android.content.Intent
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_client_local.*
import opensource.xinye.com.test11.jni.Socket
import java.io.File

class ClientLocalActivity : Activity() {
    companion object {
        fun launch(activity: Activity){
            activity.startActivity(Intent(activity,ClientLocalActivity::class.java))
        }
    }

    private lateinit var mSocketHelper: SocketHelper
    private lateinit var mSocket: Socket

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_client_local)

        mSocket = Socket({
            mSocketHelper.logMessage(it)
        })

        mSocketHelper = SocketHelper(this,{
            val name = name.text.toString().trim()
            val message = message.text.toString().trim()

            if(message.length > 0){
                val socketName = if(isFileSystemSocket(name)){
                    val file = File(filesDir,name)
                    file.absolutePath
                }else{
                    name
                }

                startServerAndClient(socketName,message)

            }
        })
    }

    private fun isFileSystemSocket(name: String): Boolean{
        return name.startsWith("/")
    }

    private fun startServerAndClient(socketName: String, message: String) {
        // Server
        mSocketHelper.Task("ServerTask",{

        },{
            mSocketHelper.logMessage("Starting Server.")
            try{
                mSocket.nativeStartLocalServer(socketName)
            }catch (e: Exception){
                mSocketHelper.logMessage("Exception: ${e.message}")
            }
            mSocketHelper.logMessage("Server Terminated.")
        },{

        })


        // Client
        mSocketHelper.Task("LocalClientTask",{
            //
        },{
            mSocketHelper.logMessage("Client Starting...")
            var clientSocket: LocalSocket? = null
            try {
                /**** 执行中 -- 后台线程 ****/
                // 1.创建Socket
                clientSocket = LocalSocket()

                // 2.设置Socket命名空间
                val namespace = if(isFileSystemSocket(socketName)){
                    LocalSocketAddress.Namespace.FILESYSTEM
                }else{
                    LocalSocketAddress.Namespace.ABSTRACT
                }

                // 3.构造本地Socket地址
                val address = LocalSocketAddress(socketName,namespace)
                // 4.连接到本地Socket
                mSocketHelper.logMessage("Connecting to $socketName")
                clientSocket.connect(address)
                mSocketHelper.logMessage("Socket Connected")

                // 5.发送消息字节到socket
                val messageBytes = message.toByteArray()
                mSocketHelper.logMessage("Sending to the socket...")
                val os = clientSocket.outputStream
                os.write(messageBytes)
                mSocketHelper.logMessage("Send ${messageBytes.size} bytes:$message")

                // 6.从Socket中接收消息返回
                mSocketHelper.logMessage("Receiving from the socket...")
                val sis = clientSocket.inputStream
                val readSize = sis.read(messageBytes)

                val receivedMessage = String(messageBytes,0,readSize)
                mSocketHelper.logMessage("Received $readSize bytes:$receivedMessage")

                os.close()
                sis.close()

            }catch (e: Exception){
                val message = e.message ?: "exception occur"
                mSocketHelper.logMessage(message)
            } finally {
                clientSocket?.close()
            }

            mSocketHelper.logMessage("Client Terminated")
        },{

        }).start()
    }

    private fun startClient(ip: String, port: Int, message: String) {
        mSocketHelper.Task("ClientTask",{
                //
            },{
                mSocketHelper.logMessage("Client Starting...")
                // 执行中 -- 后台线程
                mSocket.nativeStartUdpClient(ip,port,message)

                mSocketHelper.logMessage("Client Terminated")
            },{

            }).start()
    }
}